const mysql = require('mysql2/promise');
const config = require('../config/database').mysql;

async function testSubmit() {
  try {
    // 模拟请求数据
    const goodsData = {
      description: "56436543654365",
      images: ["/api/upload/images/1763042926276-d8772f50-652c-4d11-b6ad-999c1c361e09.png"],
      price: "56",
      originalPrice: "555",
      categoryId: 2,
      specs: {
        "商品状态": "9成新",
        "购买时间": "2021-09-10",
        "保修情况": "不保修",
        "配件情况": "654365"
      },
      tradeType: "上门自提",
      tradeDetails: "4325436565436543654365365765765"
    };

    console.log('开始测试商品提交...');
    
    // 创建数据库连接
    const connection = await mysql.createConnection({
      host: config.host,
      user: config.user,
      password: config.password,
      database: config.database,
      port: config.port
    });
    
    try {
        // 使用现有的卖家ID来避免外键约束问题
        const sellerId = 'seller_001';
        console.log(`使用现有卖家ID: ${sellerId}`);
        
        // 直接执行SQL插入商品基本信息，使用正确的列名和添加必填字段
        // 先生成商品ID
        const goodsId = 'goods_' + Date.now();
        
        const goodsResult = await connection.query(
          `INSERT INTO bid_goods 
           (id, seller_id, type, trade_type, trade_details, title, description, category_id, current_price, original_price, image, status, created_at, updated_at)
           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
          [
            goodsId, // 使用预先生成的ID
            sellerId, // 使用现有卖家ID
            'secondhand', // 商品类型
            goodsData.tradeType,
            goodsData.tradeDetails,
            goodsData.description.substring(0, 20) + '...', // 截取部分描述作为标题
            goodsData.description,
            goodsData.categoryId,
            goodsData.price,
            goodsData.originalPrice,
            goodsData.images[0],
            'published' // 商品状态
          ]
        );
      console.log(`成功插入商品基本信息，商品ID: ${goodsId}`);
      
      // 插入商品属性，使用正确的列名
      if (goodsData.specs && typeof goodsData.specs === 'object') {
        const specsEntries = Object.entries(goodsData.specs);
        for (const [key, value] of specsEntries) {
          await connection.query(
            `INSERT INTO bid_goods_attributes (goods_id, attr_key, attr_value, created_at) VALUES (?, ?, ?, NOW())`,
            [goodsId, key, value]
          );
          console.log(`成功插入属性: ${key} = ${value}`);
        }
      }
      
      console.log('✅ 测试成功! 商品数据已成功插入数据库');
      
      // 查询插入的数据进行验证
      const [goods] = await connection.query('SELECT * FROM bid_goods WHERE id = ?', [goodsId]);
      const [attributes] = await connection.query('SELECT * FROM bid_goods_attributes WHERE goods_id = ?', [goodsId]);
      
      console.log('\n插入的商品信息:');
      console.log(goods[0]);
      console.log('\n插入的属性信息:');
      console.log(attributes);
      
    } catch (error) {
      console.error('❌ 测试失败:', error.message);
    } finally {
      // 关闭连接
      await connection.end();
    }
  } catch (error) {
    console.error('❌ 数据库连接失败:', error.message);
  }
}

testSubmit().then(() => {
  console.log('\n测试完成');
  process.exit(0);
});